import { defineStore } from 'pinia'
import {ref,computed} from 'vue'
export const useCounterStore = defineStore('counter', () => {
  const cartList = ref([])
  const addItem =(playload)=>{
     const index = cartList.value.findIndex(item=>item.id==playload.id)
     if(index>-1)
     {
        return cartList.value[index].count++
     }else{
        return cartList.value.push({
            ...playload,
            count:1,
            isChecked:false
        })
     }
  }
  const delItem=(id)=>{
    cartList.value=cartList.value.filter(item=>item.id !=id)
  }

  const totalCount =computed(()=>{
     let res =0;
     cartList.value.forEach(item=>{
        res+=item.count
     })
     return res
  })
  const totalPrice =computed(()=>{
     let res =0;
     cartList.value.forEach(item=>{
        if(item.isChecked==true)
        {
           res+=item.count*item.price
        }
       
     })
     return res
  })
  const updateCount =(id,count)=>{
     cartList.value.find(item=>item.id==id).count = count
  }
  return {cartList,addItem ,delItem,totalCount,totalPrice,updateCount }
},{
    persist:true
})